package com.corner.testPackage;

import com.alibaba.fastjson2.JSON;
import com.corner.CornerApplication;
import com.corner.common.core.domain.entity.SysUser;
import com.corner.common.core.domain.model.RegisterBody;
import com.corner.common.exception.GlobalException;
import com.corner.common.utils.SecurityUtils;
import com.corner.framework.web.service.SysRegisterService;
import com.corner.system.domain.Device;
import com.corner.system.domain.FarmerUser;
import com.corner.system.domain.OperationLog;
import com.corner.system.domain.Subsidy;
import com.corner.system.domain.vo.EditUserInfoValuesVo;
import com.corner.system.domain.vo.EditUserInfoVo;
import com.corner.system.domain.vo.transferQueryVo;
import com.corner.system.domain.vo.transferRepVo;
import com.corner.system.mapper.*;
import com.corner.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * @program: corner-admin
 * @description:
 * @author: lydms
 * @create: 2022-12-30 12:43
 **/

@SpringBootTest(classes= CornerApplication.class)
@RunWith(SpringRunner.class)
public class mtest1 {

    @Autowired
    private WxgzhService wxgzhService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IoData_1Service ioData1Service;
    @Autowired
    private IoTData_1Mapper ioTData1Mapper;
    @Autowired
    private SubsidyMapper subsidyMapper;
    @Autowired
    private AliMessageService aliMessageService;
    @Value("${ALI_MESSAGE.SIGN_NAME}")
    public String SIGN_NAME;
    @Value("${ALI_MESSAGE.TEMPLATE_CODE}")
    public String TEMPLATE_CODE;
    @Value("${ALI_MESSAGE.TEMPLATE_PARAM}")
    public String TEMPLATE_PARAM;
    @Autowired
    private FarmerUserService farmerUserService;
    @Autowired
    private SubsidyTempService subsidyTempService;

    @Autowired
    OperationLogMapper operationLogMapper;
    @Autowired
    TransferBatchesService transferBatchesService;

    @Test
    public void a() throws Exception {

        transferQueryVo q = new transferQueryVo();
        //q.setMapLabel("呼兰");
        List<transferRepVo> transferRepVos = transferBatchesService.selectTransferBatches(q);
        System.out.println(transferRepVos);
    }

    @Test
    public void b()throws Exception{
        String accessToken = wxgzhService.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token="+accessToken;
        HashMap<Object, Object> requestMap = new HashMap<>();
        requestMap.put("media_id","9tWAj146XGjxVfLx9SvQoB9lgqzSLVZ6pJvpAqyAcaRoDkfrLtJsk7yNEa3FM-z2");


        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, requestMap, String.class);
        String body = responseEntity.getBody();
        System.out.println(body);
        Map parse1 = (Map)JSON.parse(body);
        Map item = (Map)parse1.get("news_item");

    }

    public static void main(String[] args) {
        List list = new ArrayList<>();
        LocalDate currentDate = LocalDate.now();
        for(int i = 0; i <= 2; i++){
            LocalDate currentDate1 = currentDate;
            if(i>0){
                currentDate1 = currentDate.minusMonths(i);
            }
            int currentyear = currentDate1.getYear();
            int currentmonthint = currentDate1.getMonthValue();
            String currentmonth = String.format("%02d", currentmonthint);
            String yearAndMonth = currentyear+"-"+currentmonth;
            list.add(yearAndMonth);
            System.out.println(yearAndMonth);
        }



        /*LocalDate currentDate = LocalDate.now();
        int currentmonth = currentDate.getMonthValue();
        int currentyearint = currentDate.getYear();
        String currentyear = String.format("%02d", currentyearint);
        LocalDate lastmonthDate = currentDate.minusMonths(1);
        int lastmonthYear = lastmonthDate.getYear();
        int lastmonthMonthint = lastmonthDate.getMonthValue();
        String lastmonthMonth = String.format("%02d", lastmonthMonthint);
        LocalDate beforeLastmonthDate = lastmonthDate.minusMonths(1);
        int beforeLastmonthYear = beforeLastmonthDate.getYear();
        int beforeLastmonthMonthint = beforeLastmonthDate.getMonthValue();
        String beforeLastmonthMonth = String.format("%02d", beforeLastmonthMonthint);

        System.out.println(currentyear+"-"+currentmonth);
        System.out.println(lastmonthYear+"-"+lastmonthMonth);
        System.out.println(beforeLastmonthYear+"-"+beforeLastmonthMonth);*/
    }


    @Test
    public void createMenu(){
        List<String> settlementMonths = new ArrayList();
        settlementMonths.add("2023-06");
        settlementMonths.add("2023-07");
        settlementMonths.add("2023-08");
        BigDecimal totalAmount = new BigDecimal("0");
        for(String settlementMonth:settlementMonths){
            //查询每月电费，并创建每月的补贴数据
            String[] split = settlementMonth.split("-");
            Map num3num5 = ioTData1Mapper.getDataByYearAndMonth("322050002030_dayStatistics", split[0], split[1]);
            BigDecimal bigNum5 = (BigDecimal) num3num5.get("num5");//电费
            BigDecimal rounddown = bigNum5.setScale(2, BigDecimal.ROUND_DOWN);
            BigDecimal num5Fen = rounddown.multiply(new BigDecimal(100)).stripTrailingZeros();
            totalAmount = totalAmount.add(num5Fen);
            System.out.println(num5Fen);

        }
        System.out.println(totalAmount);
    }

    @Test
    public void subsidyBatchInsertTest(){
        List<Subsidy> subsidyList = new ArrayList<>();
        Subsidy subsidy = new Subsidy();
        subsidy.setAmount(new BigDecimal("520"));
        subsidy.setBelongMonth("2023-06");
        subsidy.setApplyTime(new Date());
        subsidy.setDeviceId("322100004118_dayStatistics");
        subsidy.setCreateTime(new Date());
        subsidy.setStatus("0");
        int i = subsidyMapper.insertSubsidy(subsidy);
        System.out.println(subsidy);
        System.out.println(i);
        //subsidyList.add(subsidy);
        Subsidy subsidy1 = new Subsidy();
        subsidy1.setAmount(new BigDecimal("1314"));
        subsidy1.setBelongMonth("2023-05");
        subsidy1.setApplyTime(new Date());
        subsidy1.setDeviceId("322100004118_dayStatistics");
        subsidy1.setCreateTime(new Date());
        subsidy1.setStatus("0");
        int i1 = subsidyMapper.insertSubsidy(subsidy1);
        System.out.println(subsidy1);
        System.out.println(i1);
        //subsidyList.add(subsidy1);
        Subsidy subsidy2 = new Subsidy();
        subsidy2.setAmount(new BigDecimal("1400"));
        subsidy2.setBelongMonth("2023-04");
        subsidy2.setApplyTime(new Date());
        subsidy2.setDeviceId("322100004118_dayStatistics");
        subsidy2.setCreateTime(new Date());
        subsidy2.setStatus("0");
        int i2 = subsidyMapper.insertSubsidy(subsidy2);
        System.out.println(subsidy2);
        System.out.println(i2);

        Subsidy subsidy3 = new Subsidy();
        subsidy3.setAmount(new BigDecimal("1400"));
        subsidy3.setBelongMonth("2023-03");
        subsidy3.setApplyTime(new Date());
        subsidy3.setDeviceId("322100004118_dayStatistics");
        subsidy3.setCreateTime(new Date());
        subsidy3.setStatus("0");
        int i3 = subsidyMapper.insertSubsidy(subsidy3);
        System.out.println(subsidy3);
        System.out.println(i3);
        Subsidy subsidy4 = new Subsidy();
        subsidy4.setAmount(new BigDecimal("3310"));
        subsidy4.setBelongMonth("2023-02");
        subsidy4.setApplyTime(new Date());
        subsidy4.setDeviceId("322100004118_dayStatistics");
        subsidy4.setCreateTime(new Date());
        subsidy4.setStatus("0");
        int i4 = subsidyMapper.insertSubsidy(subsidy4);
        System.out.println(subsidy4);
        System.out.println(i4);
        Subsidy subsidy5 = new Subsidy();
        subsidy5.setAmount(new BigDecimal("2650"));
        subsidy5.setBelongMonth("2023-01");
        subsidy5.setApplyTime(new Date());
        subsidy5.setDeviceId("322100004118_dayStatistics");
        subsidy5.setCreateTime(new Date());
        subsidy5.setStatus("0");
        int i5 = subsidyMapper.insertSubsidy(subsidy5);
        System.out.println(subsidy5);
        System.out.println(i5);
        //subsidyList.add(subsidy2);
        //int i = subsidyMapper.insertSubsidyBatch(subsidyList);
        //System.out.println(i);


    }


    @Test
    public void updateSubBatch(){
        List<Subsidy> objects = new ArrayList<>();
        for(int i = 1; i <=3 ; i++){
            Subsidy subsidy = new Subsidy();
            subsidy.setId((long) i);
            subsidy.setStatus("2");
            objects.add(subsidy);
        }
        int i = subsidyMapper.updateSubsidyBatch(objects);
        System.out.println(i);


    }

    @Autowired
    SubsidyService subsidyService;
    @Autowired
    SysRegisterService registerService;

    @Test
    public void registerUser(){
        RegisterBody registerBody = new RegisterBody();
        registerBody.setUsername("testuser2");
        registerBody.setPassword("123456");

        String register = registerService.register(registerBody);
        System.out.println(register);
    }

    @Test
    public void insertSubBatch(){
        Map m1 = new HashMap<>();
        m1.put("deviceId","322110004214_dayStatistics");
        m1.put("electricity","13.55");
        m1.put("amount","25.91");
        m1.put("settlementYear","2023");
        m1.put("settlementMonth","8");

        /*Map m2 = new HashMap<>();
        m2.put("deviceId","121313");
        m2.put("settlementMonth","2023-08");
        m2.put("num3","31.79");
        m2.put("num5","13.36");
        Map m3 = new HashMap<>();
        m3.put("deviceId","121313");
        m3.put("settlementMonth","2023-06");
        m3.put("num3","15.91");
        m3.put("num5","26.64");*/
        List l = new ArrayList<>();
        l.add(m1);
//        l.add(m2);
//        l.add(m3);
        String approval = subsidyService.approvalBatch(l,21l);
        System.out.println(approval);


    }



    @Test
    public void selectUserSubsidy()throws Exception{
        Subsidy subsidy = new Subsidy();
        subsidy.setDeviceId("121313");
        subsidy.setApprovalFlag("0");
        //subsidy.setStatus("0");
        List<Subsidy> subsidyList = subsidyService.selectSubsidy(subsidy);
        System.out.println(subsidyList);


    }
    @Autowired
    SubsidyTempMapper subsidyTempMapper;
    @Autowired
    ApprovalMapper approvalMapper;
    @Autowired
    ApprovalService approvalService;
    @Autowired
    SysUserMapper userMapper;
    @Autowired
    FarmerUserMapper farmerUserMapper;

    @Test
    public void testtest(){

//        String username = "15134592233";
        String username = "";
        SysUser user = userMapper.selectUserByUserName(username);
        String openid = "oyl1k6GFpXkW7dtRs-9Id8aD_DLo";
        if(openid == null){
            throw new RuntimeException("无OPENID");
        }
        //用户是否已关注公众号
        SysUser sysUserByOpenId = userMapper.selectByOpenId(openid);
        if(sysUserByOpenId == null ){
            throw new RuntimeException("请先关注公众号");
        }

        // 查看用户是否已经绑定手机号和农户id
        if(StringUtils.isBlank(sysUserByOpenId.getUserName())){

            //查询设备表中是否有该手机号
            FarmerUser query = new FarmerUser();
            query.setTelephone("15134592233");
            List<FarmerUser> farmerUserList = farmerUserMapper.selectFarmerUser(query);
            if(farmerUserList == null || farmerUserList.size() == 0){
                throw new RuntimeException("未查询到此手机号码");
            }
            // 如果未绑定手机号，先校验这个手机号是否已经被其他人绑定
            if (user != null && !user.getOpenId().equals(openid)){
                throw new RuntimeException("该手机号以被其他微信账号绑定");
            }
            // 需要将手机号和用户名更新到user表中
            sysUserByOpenId.setUserName(username);
            //sysUser.setFarmerId(farmerUser.getFarmerId());
            sysUserByOpenId.setTelephoneNumber(username);
            sysUserByOpenId.setPassword(SecurityUtils.encryptPassword("123"));
            userMapper.updateUser(sysUserByOpenId);
        }else{
            // 已经绑定手机号了
            // 校验手机号与原绑定号是否一致
            if(!sysUserByOpenId.getUserName().equals(username)){
                throw new GlobalException("您输入的手机号有误，如需更改，请登陆后在用户中心申请修改");
            }
        }


    }

    @Test
    public void registeruser(){
        SysUser user = new SysUser();
        user.setUserId(1l);
        user.setUserName("管理员");
        EditUserInfoVo editUserInfoVo = new EditUserInfoVo();
        editUserInfoVo.setFarmerId(16l);
        editUserInfoVo.setFarmerName("王五");
        editUserInfoVo.setOperationType("1");
        editUserInfoVo.setOperationWay("1");
        EditUserInfoValuesVo e1 = new EditUserInfoValuesVo();
        e1.setOldValue("13888888888");
        e1.setNewValue("13999999999");
        e1.setEditType("3");
        EditUserInfoValuesVo e2 = new EditUserInfoValuesVo();
        e2.setOldValue("崔立刚");
        e2.setNewValue("崔永熙");
        e2.setEditType("1");
        EditUserInfoValuesVo e3 = new EditUserInfoValuesVo();
        e3.setOldValue("北京市丰台区二里河");
        e3.setNewValue("哈尔滨市道里区四方台大道");
        e3.setEditType("4");
        List list = new ArrayList();
        list.add(e1);
        list.add(e2);
        list.add(e3);
        editUserInfoVo.setEditUserInfoValuesVos(list);


        if(editUserInfoVo.getFarmerId() == null){
            throw new GlobalException("farmerId为空！");
        }
        if(editUserInfoVo.getFarmerName() == null){
            throw new GlobalException("farmerName为空！");
        }

        OperationLog operationLog = new OperationLog();
        FarmerUser farmerUser = new FarmerUser();
        StringBuffer sb = new StringBuffer();

        farmerUser.setFarmerId(editUserInfoVo.getFarmerId());
        operationLog.setFarmerUserId(editUserInfoVo.getFarmerId());
        operationLog.setOperatorId(user.getUserId());
        operationLog.setOperatorName(user.getUserName());
        operationLog.setOperationTime(new Date());
        operationLog.setOperationType(editUserInfoVo.getOperationType());
        operationLog.setOperationWay(editUserInfoVo.getOperationWay());

        sb.append("用户："+ editUserInfoVo.getFarmerName()+" 通过");

        String operationWay = editUserInfoVo.getOperationWay();
        if("1".equals(operationWay)){
            sb.append("公众号，");
        }else if("2".equals(operationWay)){
            sb.append("服务热线，");
        }


        List<EditUserInfoValuesVo> editUserInfoValuesVos = editUserInfoVo.getEditUserInfoValuesVos();
        for(EditUserInfoValuesVo euv: editUserInfoValuesVos){
            // 1姓名 2身份证号 3电话号 4家庭住址 5家庭成员数量 6性别
            String editType = euv.getEditType();
            String oldValue = euv.getOldValue();
            String newValue = euv.getNewValue();

            switch (editType){
                case "1":
                    farmerUser.setFarmerName(newValue);
                    sb.append("将姓名由\""+oldValue+"\"修改为\""+newValue+"\"\n");
                    break;
                case "2":
                    farmerUser.setIdCard(newValue);
                    sb.append("将身份证号由\""+oldValue+"\"修改为\""+newValue+"\"\n");
                    break;
                case "3":
                    farmerUser.setTelephone(newValue);
                    sb.append("将手机号由\""+oldValue+"\"修改为\""+newValue+"\"\n");
                    break;
                case "4":
                    farmerUser.setAddress(newValue);
                    sb.append("将家庭住址由\""+oldValue+"\"修改为\""+newValue+"\"\n");
                    break;
                case "5":
                    farmerUser.setFamilyMembers(Integer.valueOf(newValue));
                    sb.append("将5家庭成员数量由"+oldValue+"人修改为"+newValue+"人\n");
                    break;
                case "6":
                    farmerUser.setIdCard(newValue);
                    sb.append("将性别由\""+oldValue+"\"修改为\""+newValue+"\"\n");
                    break;
            }

        }

        String details = sb.toString();
        operationLog.setDetails(details);
        System.out.println(farmerUser);
        System.out.println(operationLog.getDetails());
    }


}
